extends Node
class_name CropSystem

var crops_def := {}
var time_system: TimeSystem

signal crop_ready_to_harvest(pos: Vector2i)
signal crop_withered(pos: Vector2i)

func _ready():
	load_crop_definitions()

func load_crop_definitions():
	var file := FileAccess.open("res://data/crops.json", FileAccess.READ)
	if file == null:
		print("Error: Could not load crops.json")
		return
	
	var text := file.get_as_text()
	file.close()
	
	var json := JSON.new()
	var parse_result := json.parse(text)
	
	if parse_result != OK:
		print("Error parsing crops.json")
		return
	
	var crops_array = json.data
	for crop in crops_array:
		crops_def[crop.id] = crop
	
	print("Loaded %d crop definitions" % crops_def.size())

func set_time_system(ts: TimeSystem):
	time_system = ts

func get_crop_def(crop_id: String) -> Dictionary:
	return crops_def.get(crop_id, {})

func update_tile_growth(tile_data: Dictionary, current_time: int):
	if tile_data.get("crop_id", null) == null:
		return
	
	var crop_def = get_crop_def(tile_data.crop_id)
	if crop_def.is_empty():
		return
	
	var planted_time = tile_data.get("planted_time", 0)
	var hours_passed = current_time - planted_time
	
	# 计算当前应该在哪个阶段
	var total_hours = 0
	var target_stage = 0
	
	for stage_duration in crop_def.stage_hours:
		total_hours += stage_duration
		if hours_passed >= total_hours:
			target_stage += 1
		else:
			break
	
	# 限制阶段不超过最大值
	target_stage = min(target_stage, crop_def.stage_hours.size())
	tile_data.stage = target_stage
	
	# 检查是否需要浇水
	var last_water = tile_data.get("last_water_time", planted_time)
	var hours_without_water = current_time - last_water
	
	if hours_without_water > crop_def.get("wither_hours_without_water", 24):
		# 作物枯萎
		tile_data.crop_id = null
		tile_data.stage = 0
		crop_withered.emit(Vector2i(0, 0))  # 需要传入实际位置
	elif target_stage >= crop_def.stage_hours.size():
		# 作物成熟
		crop_ready_to_harvest.emit(Vector2i(0, 0))  # 需要传入实际位置

func is_crop_mature(tile_data: Dictionary) -> bool:
	if tile_data.get("crop_id", null) == null:
		return false
	
	var crop_def = get_crop_def(tile_data.crop_id)
	if crop_def.is_empty():
		return false
	
	return tile_data.get("stage", 0) >= crop_def.stage_hours.size()

func get_crop_name(crop_id: String) -> String:
	var crop_def = get_crop_def(crop_id)
	return crop_def.get("name", "未知作物")

func get_seed_price(seed_id: String) -> int:
	for crop_def in crops_def.values():
		if crop_def.seed_item_id == seed_id:
			return crop_def.buy_price
	return 0

func get_crop_sell_price(crop_id: String) -> int:
	var crop_def = get_crop_def(crop_id)
	return crop_def.get("sell_price", 0)